package com.bieber.server.executor;

import com.bieber.server.Transporter;
import com.bieber.server.Acceptor;
import com.bieber.server.exception.FileTransportException;
import com.bieber.server.exception.RemoteException;
import com.bieber.server.pack.FilePackage;
import io.netty.channel.Channel;

/**
 * Created by bieber on 2015/8/19.
 */
public class ChannelTask implements Runnable{

    private Channel channel;

    private FilePackage filePackage;

    public ChannelTask(Channel channel, FilePackage filePackage) {
        this.channel = channel;
        this.filePackage = filePackage;
    }

    @Override
    public void run() {
        synchronized (channel){
            switch (filePackage.getStatus()){
                case START_WRITE:{
                    Transporter.registerAcceptor(channel, filePackage);
                    break;
                }
                case WRITE_CONTENT:{
                    Acceptor writer = Transporter.getAcceptor(channel);
                    if(writer==null){

                    }else{
                        try {
                            writer.acceptFile(filePackage.getOffset(), filePackage.getContent().array());
                        } catch (FileTransportException e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                }
                case END_WRITE:{
                    Acceptor writer = Transporter.getAcceptor(channel);
                    try {
                        writer.finished();
                    } catch (FileTransportException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case ERROR:{
                    throw new RemoteException(filePackage.getException());
                }
            }
        }
    }
}
